/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 14:11:17
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-08-30 17:33:10
 * @FilePath: \keep_motion_api\models\menu\permission.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 权限模型
const permissionSchema = new Schema({
  name: String,
  code: { type: String, required: true, unique: true },
  menu_item: { 
    type: Schema.Types.ObjectId, 
    ref: 'Menu' 
  },
  api_paths: [String]
});

// 获取权限
permissionSchema.statics.getPermission = async function (name = '', code = '', menu_item = '', offset = 0, limit = 10) {
  try {    
    const query = {};
    if (name) {
      const escapedName = escapeRegex(name);
      query.name = { $regex: escapedName, $options: 'i' };
    }
    if (code) {
      const escapedCode = escapeRegex(code);
      query.code = { $regex: escapedCode, $options: 'i' };
    }
    if (menu_item) {
      query.menu_item = menu_item;
    }
    // 先统计符合条件的记录总数
    const total = await this.countDocuments(query);
    // 再进行分页查询
    const rows = await this.find(query)
      .skip(Number(offset))
      .limit(Number(limit));
    return { rows, total };
  } catch (error) {
    throw error;
  }
}
// 同步菜单到权限
permissionSchema.statics.syncMenuToPermission = async function () {
  try {
    const {Menu} = require('./');
    const menuItems = await Menu.find({ component: { $exists: true, $ne: null, $ne: '' } });
    for (const menuItem of menuItems) {
      const permission = await this.findOne({ menu_item: menuItem._id });
      if (!permission) {
        await this.create({
          name: menuItem.name,
          code: menuItem.path,
          menu_item: menuItem._id,
          api_paths: []
        });
      }
    }
  } catch (error) {
    throw error;
  }
}
// 绑定API到权限
permissionSchema.statics.bindApiToPermission = async function (_id, apiPaths) {
  try {
    const permission = await this.findByIdAndUpdate(_id , { api_paths: apiPaths });
    return permission;
  } catch (error) {
    throw error;
  }
}



module.exports = mongoose.model('Permission', permissionSchema);
